package com.atguigu.gmall.mes.controller;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.MessageException;
import com.atguigu.gmall.mes.consts.ServiceConst;
import com.atguigu.gmall.mes.utils.HttpUtils;
import com.atguigu.gmall.mes.utils.MesProperties;
import com.atguigu.gmall.mes.utils.RandomUtils;
import com.google.gson.Gson;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: xie.zh
 * @create: 2021.02.26   19:58
 * @version: 1.0
 */
@RestController
@RequestMapping("/mes/send/")
@CrossOrigin
public class SmsController {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MesProperties mesProperties;

    /**
     * 发送短信
     *
     * @param mobile
     * @return
     */
    @GetMapping("{mobile}")
    public ResponseVo sendMessage(@PathVariable String mobile) {
        //判断该手机号是否可以正常接收验证码
        //是否超过一天可以接收次数
        String codeTimesPerDay = ServiceConst.CODE_TIMES_PERDAY_PREFIX + mobile;
        String timesperDayObj = redisTemplate.opsForValue().get(codeTimesPerDay);
        Integer timeperDay = 0;
        if (timesperDayObj != null) {
            timeperDay = Integer.parseInt(timesperDayObj);
            if (timeperDay >= 5) {
                throw new MessageException("今天发送短信次数已用完");
            }
        }
        //判断一分钟内是否接收过验证码
        Boolean hasKey = redisTemplate.hasKey("code:times:perminute:" + mobile);
        if (hasKey) {
            throw new MessageException("发送短信间隔不得小于一分钟");
        }
        System.out.println();
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + mesProperties.getAppCode());
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("mobile", mobile);
        String code = RandomUtils.getSixBitRandom();
        querys.put("param", "code:" + code);
        querys.put("tpl_id", mesProperties.getTplId());
        Map<String, String> bodys = new HashMap<String, String>();

        try {
            /**
             * 重要提示如下:
             * HttpUtils请从
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/src/main/java/com/aliyun/api/gateway/demo/util/HttpUtils.java
             * 下载
             *
             * 相应的依赖请参照
             * https://github.com/aliyun/api-gateway-demo-sign-java/blob/master/pom.xml
             */
            HttpResponse response = HttpUtils.doPost(mesProperties.getHost(), mesProperties.getPath(),
                    mesProperties.getPath(), headers
                    , querys,
                    bodys);
            String content = EntityUtils.toString(response.getEntity());
            Gson gson = new Gson();
            Map map = gson.fromJson(content, Map.class);
            Object returnCode = map.get("return_code");
            System.out.println("code:" + returnCode);
            if ("00000".equals(returnCode)) {
                //在redis中记录手机号 设置过期时间一分钟【一分钟内只能发送一次验证码】
                redisTemplate.opsForValue().set(ServiceConst.CODE_TIMES_PERMINUT_PREFIX + mobile, "1", 1,
                        TimeUnit.MINUTES);
                redisTemplate.opsForValue().increment(codeTimesPerDay);
                //如果timeperDay=0 表示今天第一次开始接收，设置该键存活时间为一天
                if (timeperDay == 0) {
                    redisTemplate.expire(codeTimesPerDay, 1, TimeUnit.DAYS);
                }
                //验证码发送成功,将验证码存入redis
                redisTemplate.opsForValue().set(ServiceConst.CODE_TIMES_REGIST_PREFIX + mobile, code, 5, TimeUnit.MINUTES);
                return ResponseVo.ok();
            } else {
                throw new MessageException("短信发送失败");
            }
            //获取response的body
            //System.out.println(EntityUtils.toString(response.getEntity()));
        } catch (Exception e) {
            e.printStackTrace();
            throw new MessageException("短信发送失败");
        }
    }
}
